package com.vote.admin.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.vote.common.entity.VoteProject;
import com.vote.common.entity.VoteVisit;
import com.vote.common.enums.UserSessionEnum;
import com.vote.common.enums.VoteStatusEnum;
import com.vote.common.enums.VoteTypeEnum;
import com.vote.common.returns.RespCode;
import com.vote.common.returns.RespEntity;
import com.vote.common.service.VoteProjectService;
import com.vote.common.service.VoteVisitService;
import com.vote.common.utils.TimeUtilCustomize;
import com.vote.admin.vo.record.VoteRecord;
import com.vote.admin.vo.result.UserResult;
import com.vote.admin.vo.result.VoteListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class VoteUserIndexService {

    @Autowired
    private VoteProjectService voteProjectService;

    @Autowired
    private VoteVisitService voteVisitService;

    /**
     * 投票活动列表
     * @param pageNum
     * @param pageSize
     * @param content
     * @return
     */
    public RespEntity<VoteListResult> getVoteProjectList(Integer pageNum, Integer pageSize, String content, Integer status) {
        //查询参数构造
        QueryWrapper<VoteProject> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(content)) {
            queryWrapper.lambda().like(VoteProject::getProjectName, content);
        }
        if (Objects.nonNull(status)) {
            queryWrapper.lambda().eq(VoteProject::getProjectStatus, status);
        }
        queryWrapper.lambda().eq(VoteProject::getDeleted, 0)
            .orderByDesc(VoteProject::getId);

        //分页实现
        IPage iPage = new Page(pageNum, pageSize);
        IPage page = voteProjectService.page(iPage, queryWrapper);
        List<VoteProject> records = page.getRecords();

        //数据映射
        List<VoteRecord> voteRecordList = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(item -> {

                //投票活动基础信息
                VoteRecord voteRecord = VoteRecord.builder()
                        .id(item.getId())
                        .projectName(item.getProjectName())
                        .projectImg(item.getProjectImg())
                        .projectDesc(item.getProjectDesc())
                        .startTime(item.getProjectStart())
                        .endTime(item.getProjectEnd())
                        .build();

                //投票活动状态信息
                VoteStatusEnum statusEnum = VoteStatusEnum.getInstance(item.getProjectStatus());
                if (Objects.nonNull(statusEnum)) {
                    voteRecord.setProjectStatus(statusEnum.getStatus());
                    voteRecord.setStatusColor(statusEnum.getColor());
                    voteRecord.setButton(statusEnum.getButton());
                    voteRecord.setButtonStyle(statusEnum.getDisabled());
                    voteRecord.setHref(statusEnum.getHref());
                }

                //投票活动类型信息
                VoteTypeEnum typeEnum = VoteTypeEnum.getInstance(item.getProjectPublic());
                if (Objects.nonNull(typeEnum)) {
                    voteRecord.setProjectType(typeEnum.getType());
                    voteRecord.setTypeColor(typeEnum.getColor());
                }

                voteRecordList.add(voteRecord);
            });
        }

        //数据组装
        VoteListResult result = new VoteListResult();
        result.setPageNum(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setPageCount(page.getPages());
        result.setTotal(page.getTotal());
        result.setVoteRecordList(voteRecordList);

        return new RespEntity<>(RespCode.SUCCESS, result);
    }

    /**
     * 用户信息
     * @param session
     * @return
     */
    public RespEntity<UserResult> userInfo(HttpSession session) {
        UserResult userResult = (UserResult) session.getAttribute(UserSessionEnum.USER.getCode());
        if (Objects.isNull(userResult)) {
            return new RespEntity<>(RespCode.USER_NOT_FOUND);
        }
        return new RespEntity<>(RespCode.SUCCESS, userResult);
    }

    /**
     * 退出登陆
     * @param session
     * @return
     */
    public RespEntity signOut(HttpSession session) {
        session.removeAttribute(UserSessionEnum.USER.getCode());
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 访问量数据接入
     */
    public RespEntity visitAccess() {
        //当前时间 格式：yyyy-MM-dd HH:00:00
        String dateH = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_TIME_FORMAT_H, new Date());
        //当前时间 格式：yyyy-MM-dd
        String dateD = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_DAY_FORMAT, new Date());

        //判断当前时间记录 数据库中是否存在
        VoteVisit visit = checkExits(dateH);

        if (Objects.isNull(visit)) {
            //添加
            insertVisit(dateH, dateD);
        }else {
            //更新
            updateVisit(dateH);
        }

        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 更新访问量数据
     * @param dateH
     */
    private void updateVisit(String dateH) {
        QueryWrapper<VoteVisit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoteVisit::getDt, dateH)
                .eq(VoteVisit::getDeleted, 0);
        VoteVisit visit = voteVisitService.getOne(queryWrapper);

        Integer oldVisit = visit.getVisit();
        int newVisit = oldVisit + 1;
        visit.setVisit(newVisit);

        voteVisitService.updateById(visit);
    }

    /**
     * 添加访问量数据
     * @param dateH
     * @param dateD
     */
    private void insertVisit(String dateH, String dateD) {
        VoteVisit houseVisit = VoteVisit.builder()
                .dt(dateH)
                .dtD(dateD)
                .visit(1)
                .build();

        voteVisitService.save(houseVisit);
    }

    /**
     * 判断数据库中是否存在
     * @param dateH
     * @return
     */
    private VoteVisit checkExits(String dateH) {
        QueryWrapper<VoteVisit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoteVisit::getDt, dateH)
                .eq(VoteVisit::getDeleted, 0);

        return voteVisitService.getOne(queryWrapper);
    }

}

